﻿using System.ComponentModel;
using System.Threading;
using Wizard.UI;

namespace AppScan
{
    public partial class ProgressPage : InternalWizardPage
    {
        private readonly CreateUserContext _context;

        public ProgressPage(CreateUserContext context)
        {
            _context = context;
            InitializeComponent();
        }

        private void ProgressPage_SetActive(object sender, CancelEventArgs e)
        {
            progressBar.Value = 0;
            progressBar.Minimum = 0;
            progressBar.Maximum = 100;

            SetWizardButtons(WizardButtons.None);

            BackgroundWorker worker = new BackgroundWorker
                                          {
                                              WorkerReportsProgress = true,
                                              WorkerSupportsCancellation = false
                                          };
            worker.DoWork += worker_DoWork;
            worker.ProgressChanged += worker_ProgressChanged;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;

            worker.RunWorkerAsync(_context);
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;

            for (int i = 0; i < 100; i += 10)
            {
                // We've not actually wired up the cancel button; maybe do that later.
                if (worker.CancellationPending)
                    break;

                Thread.Sleep(200);
                worker.ReportProgress(i);
            }

            Thread.Sleep(100);
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            SetWizardButtons(WizardButtons.Back | WizardButtons.Next);
            PressButton(WizardButtons.Next);
        }

        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
        }
    }
}
